package cn.jdx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class FileController {
    @RequestMapping("/get")
    @ResponseBody
    public String get() {
        return "ok";
    }

    /*
    如果是批量上传：
        1.CommonsMultipartFile [] files 声明为数组即可
        2.表单中的所有的 <input name = "file"> name 都是 file
     */
    @RequestMapping("/upload1")
    public String uploadFile(@RequestParam CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String uploadFileName = file.getOriginalFilename();
        //[1]如果文件名称为空
        if (uploadFileName==null||uploadFileName.equals("")){
            //回到主页
            return "redirect:/ok.jsp";
        }
        System.out.println("[文件名称]:"+uploadFileName);

        //[2]上传路径保存设置
        String realPath = request.getServletContext().getRealPath("/upload");
        //如果路径不存在则创建
        File uploadedFile = new File(realPath);
        if (!uploadedFile.exists()){
            uploadedFile.mkdir();//创建文件夹
        }
        System.out.println("[保存地址]:"+realPath);

        //[3]创建文件输入和输出流对象开始读写
        InputStream inputStream = file.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(new File(realPath, uploadFileName));

        int len = 0;
        byte [] buffer = new byte[1024];
        while ((len = inputStream.read(buffer))!=-1){
            fileOutputStream.write(buffer,0,len);//写出缓冲区
            fileOutputStream.flush();
        }
        inputStream.close();
        fileOutputStream.close();
        System.out.println("[写入完成]");

        return "redirect:/ok.jsp";
    }


    /*
    采用file.transferTo()保存上传的文件
     */
    @RequestMapping("/upload2")
    public String uploadFile2(@RequestParam(name = "file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //[1]上传路径保存设置
        String realPath = request.getServletContext().getRealPath("/upload");
        //如果路径不存在则创建
        File uploadedFile = new File(realPath);
        if (!uploadedFile.exists()){
            uploadedFile.mkdir();//创建文件夹
        }
        System.out.println("[保存地址]:"+realPath);

        //直接上传
        file.transferTo(new File(realPath,file.getOriginalFilename()));

        return "ok";
    }



}
